package com.worldserver.net;

import com.report.ServerInfo;
import com.report.UserInfo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class WorldServerClient implements Runnable {
    ChannelFuture f;

    public void close() {
        //System.err.println("0channel active flag:"+f.channel().isActive());
        f.channel().close();
        //System.err.println("1channel active flag:"+f.channel().isActive());
        f.channel().close().awaitUninterruptibly();
        //System.err.println("2channel active flag:"+f.channel().isActive());

    }

    private UserInfo ui;

    public WorldServerClient(UserInfo ui) {
        this.ui = ui;
    }

    @Override public void run() {
        connection();
    }

    public void connection() {
        Bootstrap b = new Bootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        long t1 = System.currentTimeMillis();
        try {
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast("decoder", new MessageDecoder());
                            ch.pipeline().addLast("handler", new WorldServerClientHandler(ui));
                        }
                    });
            //System.err.println("ui="+ui);
            ServerInfo sinfo = ui.getDefaultServer();
            //sinfo.setIp("192.168.1.119");
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10 * 1000);

            //System.err.println("11111111111111   "+System.currentTimeMillis());
            f = b.connect(sinfo.getIp(), sinfo.getPort()).sync();
            //b.wait(2000);
            f.channel().closeFuture().sync();
            //System.err.println("22222222222222   "+(System.currentTimeMillis()-t1));
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //System.err.println("33333333333333   "+(System.currentTimeMillis()-t1));
            group.shutdownGracefully();
        }
    }

}
